package work.vcloud.baseinfo.controller.recruit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import work.vcloud.baseinfo.controller.StudentController;
import work.vcloud.baseinfo.exception.BaseException;
import work.vcloud.baseinfo.service.intfc.BatchInsertService;
import work.vcloud.baseinfo.utils.HttpUtil;
import work.vcloud.baseinfo.utils.ImportExcelUtil;
import work.vcloud.frame.controller.BaseController;
import work.vcloud.frame.dao.OpenDao;
import work.vcloud.frame.vo.OutputVo;

import javax.annotation.Resource;
import java.util.*;

/**
 * 分班
 */
@RestController
@Scope("prototype")
public class DivisionClassController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${api.passwordReceive}")
    private String passwordReceive;

    @Value("${auth.app_id}")
    private String appId;

    @Resource
    OpenDao openDao;

    @Resource
    BatchInsertService batchInsertService;

//    /**
//     * 添加学生到指定班级
//     */
//    @RequestMapping("divisionClass/addStudent")
//    public OutputVo insert() {
//        try {
//            Map<String, Object> map = getParameterMap();
//            map.remove("page");
//
//            // 在读状态id
//            String studentStateId = getstudentStateId();
//
//            // 查询班级信息
//            String fk_class = map.get("fk_class").toString();
//            map.put("sqlMapId", "class.select");
//            Map<String, Object> classMap = (Map) openDao.queryForObject(map);
//            String fk_unit = (String) classMap.get("fk_unit");
//
//            // 序列化要分班的学生数据
//            String recruitStudentArrayStr = (String) map.get("recruitStudentArrayStr");
//            JSONArray studentArray = JSON.parseArray(recruitStudentArrayStr);
//            System.out.println(studentArray);
//
//            for (int i = 0; i < studentArray.size(); i++) {
//                JSONObject student = studentArray.getJSONObject(i);
//
//                // 填充学生的信息
//                fillStudent(map, studentStateId, fk_class, fk_unit, student , fk_grade , xh);
//
//                // 判断学生是否已经存在
//                map.put("sqlMapId", "student.selectById");
//                Map oldStuMap = (Map) openDao.queryForObject(map);
//                if (oldStuMap == null) {
//                    // 添加学生
//                    map.put("sqlMapId", "divisionClass.addClassStudent");
//                    openDao.insert(map);
//                } else {
//                    // 修改
//                    map.put("sqlMapId", "divisionClass.updateClassStudent");
//                    openDao.update(map);
//                }
//
//                // 修改密码
//                String ids = map.get("fk_user").toString();
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put("ids", ids);
//                jsonObject.put("type", 2);
//                String accessToken = ((Map) session.getAttribute(appId)).get("access_token").toString();
//                HttpUtil.doPost2(passwordReceive, jsonObject, accessToken);
//            }
//
//            return output("0000");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return output("9999");
//        }
//    }

    /**
     * 获取在读状态
     *
     * @return
     * @throws Exception
     */
    private String getstudentStateId() throws Exception {
        // 获取“在读”状态id
        Map<String, Object> map = new HashMap<>();
        map.put("sqlMapId", "dictionary.selectByImport");
        map.put("fk_rule", "SJAAAAA10061");
        map.put("name", "在读");
        Map<String, Object> studentStateMap = (Map) openDao.queryForObject(map);
        String studentStateId = studentStateMap.get("id").toString();
        return studentStateId;
    }

    /**
     * 填充学生的信息
     *
     * @param map
     * @param studentStateId
     * @param fk_class
     * @param fk_unit
     * @param student
     */
    private void fillStudent(Map<String, Object> map, String studentStateId, String fk_class, String fk_unit, Map student, String fk_grade, String xh) {

        map.put("name", student.get("name"));
        map.put("fk_user", student.get("id"));
        map.put("sfzjh", student.get("sfzjh"));
        map.put("sex", student.get("sex"));
        map.put("xzz", student.get("message_address"));
        map.put("lxdh", student.get("telephone"));
        map.put("xh",xh);
        map.put("yhm", xh);
        map.put("fk_unit", fk_unit);
        map.put("fk_class", fk_class);
        map.put("fk_grade", fk_grade);
        map.put("state", studentStateId);

    }

    /**
     * 导入分班信息
     *
     * @param multipartFile
     * @param formData
     * @return
     */
    @RequestMapping("divisionClass/importClassStudent")
    public OutputVo teacherImportUpdate(@RequestParam("upfile") MultipartFile multipartFile, @RequestParam("formData") String formData) {
        try {
            Map<String, Object> map = getParameterMap();
            map.remove("page");
            if (multipartFile.isEmpty()) {
                throw new Exception("文件不存在！");
            }
            JSONObject jsonData = (JSONObject) JSON.parse(formData);

            List colList = new ArrayList();
            fillColList(colList);

            // 获取excel 数据
            List<Map<String, Object>> dataList = new ImportExcelUtil().readExcel(multipartFile.getInputStream(), colList);
            if (dataList.size() > 0 && dataList.get(0).size() != colList.size()) {
                //System.out.println("Excel表格中有多出的列！");
                throw new BaseException("Excel表格中有多出的列！");
            }
            System.out.println(dataList);

            // 在读学生状态id
            String studentStateId = getstudentStateId();
            // 班级信息（缓存）
            Map<String, Map<String, Object>> code_classMap = new HashMap();

            for (int i = 0; i < dataList.size(); i++) {
                Map<String, Object> stuClassMap = dataList.get(i);
                String sfzjh = stuClassMap.get("sfzjh").toString();
                String name = stuClassMap.get("name").toString();
                String sex = stuClassMap.get("sex").toString();
                String xh = stuClassMap.get("xh").toString();
                String class_name = stuClassMap.get("class_name").toString();

                Map<String, Object> classMap = code_classMap.get(class_name);
                if (classMap == null) {
                    map.put("fk_class", null);
                    map.put("name", class_name);
                    map.put("sqlMapId", "class.select");
                    classMap = (Map<String, Object>) openDao.queryForObject(map);
                    if (classMap == null) {
                        throw new BaseException("没有查找到班级信息：" + class_name);
                    }
                    code_classMap.put(class_name, classMap);
                }
                String fk_class = classMap.get("id").toString();
                String fk_grade = classMap.get("fk_grade").toString();
                String fk_unit = classMap.get("fk_unit").toString();

                //查询学生信息
                map.put("sfzjh", sfzjh);
                map.put("sqlMapId", "recruitStudent.findRecruitStudent");
                Map<String, Object> student = (Map<String, Object>) openDao.queryForObject(map);
                if (student == null) {
                    throw new BaseException("没有查找到已报道学生信息：" + name);
                }

                // 填充学生数据
                fillStudent(map, studentStateId, fk_class, fk_unit, student , fk_grade , xh);

                // 判断学生是否已经存在
                map.put("sqlMapId", "student.select");
                Map oldStuMap = (Map) openDao.queryForObject(map);
                if (oldStuMap == null) {
                    // 添加学生
                    map.put("sqlMapId", "divisionClass.addClassStudent");
                    openDao.insert(map);
                } else {
                    // 修改
                    map.put("sqlMapId", "divisionClass.updateClassStudent");
                    openDao.update(map);
                }

                // 修改密码
                String ids = map.get("fk_user").toString();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("ids", ids);
                jsonObject.put("type", 2);
                String accessToken = ((Map) session.getAttribute(appId)).get("access_token").toString();
                HttpUtil.doPost2(passwordReceive, jsonObject, accessToken);
            }
            return output("0000");
        } catch (BaseException e) {
            e.printStackTrace();
            return output("9999", e.getMessage(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return output("9999", "", e.getMessage().toString());
        }
    }

    private void fillColList(List colList) {
        Map tMap = new HashMap();
        tMap.put("name", "证件号码");
        tMap.put("col", "sfzjh");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "姓名");
        tMap.put("col", "name");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "性别");
        tMap.put("col", "sex");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "学号");
        tMap.put("col", "xh");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "班级名称");
        tMap.put("col", "class_name");
        colList.add(tMap);
    }

}


